Skip to main content

Topological Sorting

1. What is Topological Sorting?​

Topological Sorting is a linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge u β†’ v, vertex u comes before vertex v. It is used in scenarios where there is a dependency between tasks.

2. Algorithm for Topological Sorting​

  1. Initialize an empty stack to store the result (topologically sorted order).
  2. Mark all vertices as not visited.
  3. For each vertex, if it is not visited, call the recursive helper function:
    • Mark the current vertex as visited.
    • For each adjacent vertex, if it is not visited, recursively call the helper function.
    • Push the current vertex to the stack.
  4. Reverse the stack to get the topological order.

3. How Does Topological Sorting Work?​

  • Topological sorting sorts vertices such that for any directed edge u β†’ v, vertex u appears before vertex v in the ordering.
  • It uses depth-first search (DFS) to explore the graph and a stack to store the vertices in the topologically sorted order.

4. Problem Description​

Given a directed acyclic graph (DAG), find a topological ordering of its vertices.

5. Examples​

Example graph:

      5 β†’ 0 ← 4
↓ ↓
2 β†’ 3 β†’ 1

Topological Sort: 4, 5, 0, 2, 3, 1 or 5, 4, 2, 3, 0, 1 (one of the valid topological orders)

6. Constraints​

  • The graph must be directed and acyclic.

7. Implementation​

Topological Sorting​

def topological_sort_util(v, visited, stack, graph):
visited[v] = True
for neighbor in graph[v]:
if not visited[neighbor]:
topological_sort_util(neighbor, visited, stack, graph)
stack.append(v)

def topological_sort(graph):
visited = {v: False for v in graph}
stack = []

for v in graph:
if not visited[v]:
topological_sort_util(v, visited, stack, graph)

stack.reverse()
return stack

graph = {
5: [0, 2],
4: [0, 1],
2: [3],
3: [1],
1: [],
0: []
}

print(topological_sort(graph))

8. Complexity Analysis​

  • Time Complexity: O(V+E)O(V + E) where VV is the number of vertices and EE is the number of edges.
  • Space Complexity: O(V)O(V) due to the stack and visited array.

9. Advantages and Disadvantages​

Advantages:​

  • Efficient and straightforward for DAGs.
  • Useful for scheduling tasks, resolving symbol dependencies in linkers, etc.

Disadvantages:​

  • Only applicable to directed acyclic graphs (DAGs).
  • Does not handle graphs with cycles.

10. References​